package com.teach.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 自定义字符编码过滤器
 * @author zpw
 *
 */
public class CharsetFilter implements Filter{


	private String charset = "UTF-8";
	private String contentType = "text/html;charset=UTF-8";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {//通过init方法初始化配置
		if(filterConfig.getInitParameter("charset")!=null){      //初始化字符集，web.xml也可以配置
			charset = filterConfig.getInitParameter("charset");
		}
		
		if(filterConfig.getInitParameter("contentType")!=null){      //初始化文档类型
			contentType = filterConfig.getInitParameter("contentType");
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if(request.getCharacterEncoding()==null){   //获取请求的字符集编码
			request.setCharacterEncoding(charset);   //设置字符集编码
		}
		if(response.getContentType()==null){     //获取响应的文档类型	
			response.setContentType(contentType);	 	 //设置响应文档类型
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}
}
